package org.example;

import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 参照MVC变成规范，封装连接的打开和关闭
 */
public class HiveService {
    // 日志对象，用于记录日志信息
    static Logger logger = Logger.getLogger(HiveService.class);
    // 驱动名
    public static String driverName = "org.apache.hive.jdbc.HiveDriver";
    // URL
    public static String url = "jdbc:hive2://192.168.134.130:10000/test";
    // 用户名和密码
    public static String user = "root";
    public static String password = "Master123!!";

    /**
     * 创建连接
     * @return Connection对象，如果连接成功
     * @throws RuntimeException 如果驱动类未找到或无法建立连接
     */
    public static Connection getConn(){
        Connection conn = null;
        try {
            // 加载JDBC驱动
            Class.forName(driverName);
            // 建立数据库连接
            conn = DriverManager.getConnection(url,user,password);
            logger.info("连接成功！");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("驱动类未找到", e);
        } catch (SQLException e) {
            throw new RuntimeException("无法建立连接", e);
        }
        return conn;
    }

    /**
     * 创建Statement
     * @param connection 数据库连接对象
     * @return Statement对象，用于执行SQL语句
     * @throws SQLException 如果创建Statement失败
     */
    public static Statement getStmt(Connection connection) throws SQLException {
        // 记录调试信息
        logger.debug(connection);
        if (connection == null){
            logger.debug("连接为空！");
        }
        return connection.createStatement();
    }

    /**
     * 关闭连接
     * @param conn 数据库连接对象
     * @param stmt Statement对象
     */
    public static void close(Connection conn, Statement stmt){
        try {
            if (stmt != null){
                stmt.close();
            }
            if (conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException("关闭连接失败", e);
        }
    }
}
